<?php

namespace App\Http\Controllers;

use App\Util\Tool;
use Illuminate\Http\Request;

class BoundPhoneController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function BoundPhone(Request $request)
    {
        //判断手机号码不能为空
        if (empty($request->phone)) {
            return $this->ResultJson(0, '手机号码不能为空!', []);
        }
        //判断验证码不能为空
        if (empty($request->code)) {
            return $this->ResultJson(0, '验证码不能为空!', []);
        }
        //判断短信验证码是否过期
        $code = Tool:: GetSmsvalidator($request->phone);
        if (empty($code)) {
            return $this->ResultJson(0, '短信验证码已经过期', []);
        }
        //需要检查短信验证码是正确
        if ($request->code != $code) {
            return $this->ResultJson(0, '短信验证码错误', []);
        }
        //更新验证码为验证过了
        $this->SetCode($request->phone, $code);
        $user = Tool::ApiTokenGetDoctorUser($request->api_token);
        //检查是否登录
        if (empty($user)) {
            return $this->ResultJson(0, '请先登录后再操作!', []);
        }
        $user->account = $request->phone;
        $user->save();
        //更新token
        Tool::SetDoctorAndUpToken($request->api_token, $request->phone);
        return $this->ResultJson(1, '换绑成功!', []);
    }
}
